﻿using System.Collections;
using UnityEditor;
using UnityEngine;


public class CharacterCreator : MonoBehaviour
{
    public GameObject fbxObject;

    [Header("Preparation")]
    public CharacterController characterController;

    public void create()
    {
        try
        {
            GameObject newCharacter = InstantiateNewCharacter(fbxObject);
            newCharacter.transform.SetParent(GameObject.Find("Anubis").transform);

            newCharacter.transform.localPosition = new Vector3(0, 0, 0);
            newCharacter.transform.localRotation = new Quaternion(0, 0, 0, 0);

            newCharacter.AddComponent<NavMove>();
            newCharacter.AddComponent<BVHDriver>();

            BVHDriver bd = newCharacter.GetComponent<BVHDriver>();
            bd.targetAvatar = newCharacter.GetComponent<Animator>();

            newCharacter.tag = "Character";

            Debug.Log("Character " + newCharacter.name + " is created successfully!");

            // Add new character to controller
            characterController.characters.Add(newCharacter);
            Debug.Log(newCharacter.name + " have been added to characters list!");
        } 
        catch (System.Exception e)
        {
            Debug.LogError("new character create fail!");
            Debug.LogError(e);
        }
    }

    // Use this for initialization
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {

    }

    private GameObject InstantiateNewCharacter(GameObject selected)
    {
        if (selected == null)
        {
            return selected;
        }

        if (selected.scene.IsValid())
        {
            return selected;
        }

        return PrefabUtility.InstantiatePrefab(selected) as GameObject;
    }
}
